<template>
    <div class="profitSettlementHandle">
        <el-breadcrumb separator="/" class="bread-title">
            <el-breadcrumb-item :to="{ path: '/profitSettlement' }">利润结算标准</el-breadcrumb-item>
            <el-breadcrumb-item>{{typeMap[type]}}</el-breadcrumb-item>
        </el-breadcrumb>
        <div v-if="stepIndex === 0">
            <div>提取标准：利润结算标准</div>
            <div class="mt20 mb20">佣金来源：
                <span v-if="type==='view'">营收利润</span>
                <el-select v-else v-model="commissionSource" placeholder="请选择" size="small">
                    <el-option
                            v-for="subItem in commissionSourceOptions"
                            :key="subItem.value"
                            :label="subItem.label"
                            :value="subItem.value">
                    </el-option>
                </el-select>
            </div>
            <hr/>
            <div class="mt20">提取规则：
                <span v-if="type==='view'">基数*比例</span>
                <el-radio v-else v-model="calcParams.extractCategory" :label="2">基数*比例</el-radio>
            </div>
            <div class="mt20 mb20">计提基数：
                <span v-if="type==='view'">营收利润</span>
                <el-select v-else v-model="calcParams.extractBaseNum" placeholder="请选择" size="small">
                    <el-option
                            v-for="subItem in calcBasicOptions"
                            :key="subItem.value"
                            :label="subItem.label"
                            :value="subItem.value">
                    </el-option>
                </el-select>
            </div>
            <div class="mt20 mb20">计提方式：
                <span v-if="type==='view'">{{extractType[calcParams.extractType]}}</span>
                <el-select v-else v-model="calcParams.extractType" placeholder="请选择" size="small">
                    <el-option
                            v-for="subItem in calcTypeOptions"
                            :key="subItem.value"
                            :label="subItem.label"
                            :value="subItem.value">
                    </el-option>
                </el-select>
            </div>
            <div v-if="calcParams.extractType === 2">计提比例：
                <span v-if="type==='view'">{{calcParams.extractProportion}}</span>
                <el-input v-else style="width: 200px;" size="small" @input="checkAllProportion(calcParams.extractProportion)" v-model="calcParams.extractProportion" placeholder="请输入计提比例"></el-input>
                %
            </div>
            <div v-if="type==='view' && calcParams.extractType === 1">
                <el-table
                        :data="settleRangeList"
                        border
                        highlight-current-row
                        style="width: 400px;margin-top: 20px;">
                    <el-table-column
                            align="center"
                            label="利润区间(万元)">
                        <template slot-scope="scope">
                            <span v-if="scope.row.lowerMark === 1">
                                {{scope.row.upper}}以下
                            </span>
                            <span v-else-if="scope.row.upperMark ===1">
                                {{scope.row.lower}}以上
                            </span>
                            <span v-else>
                                {{scope.row.lower}} - {{scope.row.upper}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            property="extractProportion"
                            align="center"
                            label="计提比例">
                        <template slot-scope="scope">
                            {{scope.row.extractProportion}}%
                        </template>
                    </el-table-column>
                </el-table>

            </div>
            <div class="mt30" v-if="type!=='view'">
                <!-- 阶段计提 -->
                <div v-if="calcParams.extractType === 1">
                    <el-button @click="returnList">取消</el-button>
                    <el-button type="primary" @click="handleStep(1)">下一步</el-button>
                </div>
                <div v-else>
                    <el-button @click="returnList">取消</el-button>
                    <el-button type="primary" @click="createProjectSettle">保存</el-button>
                </div>
            </div>
        </div>
        <div v-else>
            <div style="margin: 20px 0">
                设置区间范围（利润区间-万元）：
                <i class="mr50" style="display: inline-block"></i>
                计提比例
            </div>

            <ul class="newIntervalList">
                <li>
                    <el-input type="text" @input="checkNum(newIntervalData.firstInterval, -1, 0)" :class="errorIndex === 0 ? 'is-error': ''" style="width: 100px" size="mini" v-model="newIntervalData.firstInterval"></el-input>
                    以下
                    <el-input type="text" class="w100" @input="checkExtractProportion(newIntervalData.firstExtractProportion, true, 'firstExtractProportion')" v-model="newIntervalData.firstExtractProportion" style="margin-left: 155px;" size="mini"></el-input>
                    %
                </li>
                <li v-for="(item, index) in newIntervalData.middleInterval">
                    <el-input type="text" @input="checkNum(item[0], index, 0)" :class="errorIndex === (index*2+1) ? 'is-error': ''" style="width: 100px" size="mini" v-model="item[0]"></el-input>
                    ——
                    <el-input type="text" @input="checkNum(item[1], index,1)" :class="errorIndex === (index*2+2) ? 'is-error': ''" style="width: 100px" size="mini" v-model="item[1]"></el-input>
                    <el-input type="text" class="w100 ml50" @input="checkExtractProportion(newIntervalData.middleExtractProportion[index], false, index)" v-model="newIntervalData.middleExtractProportion[index]" size="mini"></el-input>
                    %
                    <a href="javascript:;;" class="del" @click="delInterval(index)">删除</a>
                </li>
                <li>
                    <el-button type="primary" size="mini" @click="addInterval">添加
                    </el-button>
                </li>
                <li>
                    <el-input type="text" @input="checkNum(newIntervalData.lastInterval,-1, 1)" :class="errorIndex === (newIntervalData.middleInterval.length * 2 + 1) ? 'is-error': ''" style="width: 100px" size="mini" v-model="newIntervalData.lastInterval"></el-input>
                    以上
                    <el-input type="text" class="w100" @input="checkExtractProportion(newIntervalData.lastExtractProportion, true, 'lastExtractProportion')" v-model="newIntervalData.lastExtractProportion" style="margin-left: 155px;" size="mini"></el-input>
                    %
                </li>
            </ul>
            <div>
                <el-button @click="handleStep(0)">上一步</el-button>
                <el-button type="primary" @click="createProjectSettle">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import api from '@/api/apiPath'
    import {extractType} from "../fieldMap"
    //写了极蠢无比的代码
    export default {
        name: 'profitSettlementHandle',
        data() {
            return {
                type: "",
                typeMap: {
                    new: '新建',
                    edit: '编辑',
                    view: '查看'
                },
                stepIndex: 0,
                calcParams: {
                    extractCategory: 2,
                    extractBaseNum: 3,
                    extractProportion: "",
                    extractType: 1,
                },
                commissionSource: 3,
                commissionSourceOptions: [
                    {
                        value: 3,
                        label: '营收利润'
                    }
                ],
                calcTypeOptions: [
                    {
                        value: 1,
                        label: '阶段计提'
                    },
                    {
                        value: 2,
                        label: '通提'
                    }
                ],
                calcBasicOptions: [
                    {
                        value: 3,
                        label: '营收利润'
                    }
                ],
                errorIndex: "",
                newIntervalData: {
                    firstInterval: "",
                    middleInterval: [["", ""]],
                    lastInterval: "",
                    firstExtractProportion: "",
                    middleExtractProportion: [""],
                    lastExtractProportion: "",
                },
                settleRangeList: [],
                extractType
            }
        },
        created() {
            this.type = this.$route.query.type;
            if (this.type !== 'new') {
                this.viewStageExtract(this.$route.query.id)
            }
        },
        mounted() {

        },
        methods: {
            handleStep(index) {
                this.stepIndex = index;
            },
            checkNum(value, type, index) {
                value = value.replace(/[^\d]/g, '');
                if (value.indexOf('.') < 0 && value != '') {
                    value = parseInt(value);
                }
                setTimeout(() => {
                    if (type === -1) {
                        if (index === 0) {
                            this.newIntervalData.firstInterval = value
                        } else {
                            this.newIntervalData.lastInterval = value
                        }
                    } else {
                        this.$set(this.newIntervalData.middleInterval[type], index, value)
                    }
                }, 30)
            },
            returnList() {
                this.$router.push({path: "./profitSettlement"})
            },
            addInterval() {
                this.newIntervalData.middleInterval.push(["", ""])
            },
            delInterval(index) {
                this.newIntervalData.middleInterval.splice(index, 1);
                this.newIntervalData.middleExtractProportion.splice(index, 1);
            },
            checkInterval() {
                // 检测计提比例是否填写
                if (!this.newIntervalData.firstExtractProportion || !this.newIntervalData.lastExtractProportion) {
                    this.$message({
                        message: '计提比例不能为0或空！',
                        type: 'warning'
                    });
                    return false
                }
                if (this.newIntervalData.firstExtractProportion <= 0 || this.newIntervalData.firstExtractProportion >= 100 || this.newIntervalData.lastExtractProportion <= 0 || this.newIntervalData.lastExtractProportion >= 100) {
                    this.$message({
                        message: '计提比例必须大于0小于100!',
                        type: 'warning'
                    });
                    return false
                }
                this.errorIndex = '';
                if (!this.newIntervalData.firstInterval) {
                    this.errorIndex = 0
                    this.$message({
                        message: '以下区间不能为0或空！',
                        type: 'warning'
                    });
                    return false
                }
                let rangeList = [{
                    upper: this.newIntervalData.firstInterval,
                    extractProportion: this.newIntervalData.firstExtractProportion,
                    lowerMark: 1,
                    upperMark: 0
                }]

                for (let i = 0, len = this.newIntervalData.middleInterval.length; i < len; i++) {
                    let item = this.newIntervalData.middleInterval[i];
                    let afterItem = "";

                    if (!item[0]) {
                        this.errorIndex = i * 2 + 1;
                        this.$message({
                            message: '区间内容不能为0或空！',
                            type: 'warning'
                        });
                        return false;
                    }
                    if (!item[1]) {
                        this.errorIndex = i * 2 + 2;
                        this.$message({
                            message: '区间内容不能为0或空！',
                            type: 'warning'
                        });
                        return false;
                    }

                    if (+item[0] > +item[1]) {
                        this.errorIndex = i * 2 + 1;
                        this.$message({
                            message: '同一区间内容前者不能大于后者!',
                            type: 'warning'
                        });
                        return false;
                    }


                    // 判断如果小于上一区间
                    if (i === 0) {
                        afterItem = this.newIntervalData.firstInterval;
                        if (+afterItem > +item[0]) {
                            this.errorIndex = 0
                            this.$message({
                                message: '不能大于下一区间内容!',
                                type: 'warning'
                            });
                            return false;
                        }
                    } else {
                        afterItem = this.newIntervalData.middleInterval[i - 1][1];
                        if (+afterItem > +item[0]) {
                            this.errorIndex = i * 2;
                            this.$message({
                                message: '不能大于下一区间内容!',
                                type: 'warning'
                            });
                            return false;
                        }
                    }
                    rangeList.push({
                        lower: item[0],
                        upper: item[1],
                        extractProportion: this.newIntervalData.middleExtractProportion[i],
                        lowerMark: 0,
                        upperMark: 0
                    })
                }

                if (!this.newIntervalData.lastInterval) {
                    this.errorIndex = this.newIntervalData.middleInterval.length * 2 + 1
                    this.$message({
                        message: '以上区间不能为0或空!',
                        type: 'warning'
                    });
                    return false
                }
                let length = this.newIntervalData.middleInterval.length;
                if (+this.newIntervalData.lastInterval < +this.newIntervalData.middleInterval[length - 1][1]) {
                    this.errorIndex = this.errorIndex = length * 2;
                    this.$message({
                        message: '不能大于下一区间内容!',
                        type: 'warning'
                    });
                    return false
                }

                rangeList.push({
                    lower: this.newIntervalData.lastInterval,
                    extractProportion: this.newIntervalData.lastExtractProportion,
                    lowerMark: 0,
                    upperMark: 1
                })
                return rangeList
            },
            createProjectSettle() {
                let settleRangeList = []
                if (this.calcParams.extractType === 2) {
                    if (this.calcParams.extractProportion) {
                        if (+this.calcParams.extractProportion <= 0 || +this.calcParams.extractProportion >= 100) {
                            this.$message({
                                message: '计提比例必须大于0小于100!',
                                type: 'warning'
                            });
                            return false
                        }
                    } else {
                        this.$message({
                            message: '计提比例不能为0或空!',
                            type: 'warning'
                        });
                        return false;
                    }
                } else {
                    let rangeList = this.checkInterval();
                    if (rangeList) {
                        settleRangeList = this.checkInterval();
                    } else {
                        return false;
                    }
                }
                this.axios.post(api.createProjectSettle, {
                    extractStandard: 4,
                    commSource: this.commissionSource,
                    extractBaseNum: this.calcParams.extractBaseNum,
                    extractType: this.calcParams.extractType,
                    extractProportion: this.calcParams.extractProportion,
                    extractCategory: this.calcParams.extractCategory,
                    settleRangeList: settleRangeList
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            message: this.typeMap[this.type] + "成功",
                            type: 'success'
                        });
                        this.returnList();
                    }
                })
            },
            replaceNum(value) {
                value = value.replace(/[^\d.]/g, '');
                value = value.replace(/\.{2,}/g, ".");
                value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
                value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
                if (value.indexOf('.') < 0 && value != '') {
                    value = parseInt(value);
                }
                return value
            },
            checkExtractProportion(value, type, field) {
                value = this.replaceNum(value);
                setTimeout(() => {
                    if (type) {
                        this.$set(this.newIntervalData, field, value)
                    } else {
                        this.$set(this.newIntervalData.middleExtractProportion, field, value)
                    }
                }, 30)
            },
            checkAllProportion(value) {
                value = this.replaceNum(value);
                setTimeout(() => {
                    this.$set(this.calcParams, 'extractProportion', value)
                }, 30)
            },

            viewStageExtract(id) {
                this.axios.post(api.viewStageExtract, {
                    settleId: id
                }).then((res) => {
                    let data = res.data.data;
                    this.calcParams = {
                        extractCategory: data.extractCategory,
                        extractBaseNum: data.extractBaseNum,
                        extractProportion: data.extractProportion,
                        extractType: data.extractType,
                    }
                    if (data.settleRangeList && data.settleRangeList.length) {
                        this.settleRangeList = data.settleRangeList;
                        data.settleRangeList.forEach((item, index) => {
                            if (item.lowerMark === 1) {// XXX以下
                                this.newIntervalData.firstInterval = item.upper;
                                this.newIntervalData.firstExtractProportion = item.extractProportion;
                            } else if (item.upperMark === 1) {// XXX以上
                                this.newIntervalData.lastInterval = item.lower;
                                this.newIntervalData.lastExtractProportion = item.extractProportion;
                            } else {//普通的
                                if (!(this.newIntervalData.middleInterval[index - 1] instanceof Array)) {
                                    this.$set(this.newIntervalData.middleInterval, [index - 1], []);
                                }
                                this.$set(this.newIntervalData.middleInterval[index - 1], 0, item.lower);
                                this.$set(this.newIntervalData.middleInterval[index - 1], 1, item.upper);
                                this.$set(this.newIntervalData.middleExtractProportion, index - 1, item.extractProportion);
                            }
                        })
                    }
                })
            },
        },
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus">
    .newIntervalList {
        list-style: none;
        padding: 0;
        li {
            margin-top: 20px;
            a {
                text-decoration: none;
                margin: 0 10px;
            }
            .del {
                color: #f00;
                margin-left: 20px;
            }
            .is-error {
                input {
                    border-color: #f56c6c !important;
                    box-shadow: 1px 1px 10px #f00;
                }
            }
        }
    }
</style>
